package com.supergzt.service.impl;

import com.google.code.kaptcha.Producer;
import com.supergzt.constant.TokenConstants;
import com.supergzt.service.KaptchaService;
import com.supergzt.service.RedissonService;
import com.supergzt.utils.KeyUtils;
import com.supergzt.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 张钧
 * @Description
 * @create 2023-03-30 10:37
 */
@Service
public class KaptchaServiceImpl implements KaptchaService {
	@Resource
	private Producer captchaProducer;

	@Resource
	private RedissonService redissonService;

	@Override
	public void getKaptchaImage(HttpServletResponse response, String oldUUID) throws IOException {
		if(StringUtils.isNotNull(oldUUID)){
			redissonService.removeString(KeyUtils.createCode(oldUUID));
		}
		String uuid = UUID.randomUUID().toString();
		response.setDateHeader("Expires", TokenConstants.KAPTCHA_EXPIRE_TIME);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.addHeader("uuid", uuid);
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		response.setHeader("Access-Control-Expose-Headers", "uuid");
		String capText = captchaProducer.createText();
		redissonService.setString(KeyUtils.createCode(uuid),capText,TokenConstants.KAPTCHA_EXPIRE_TIME);
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		try (out) {
			ImageIO.write(bi, "jpg", out);
			out.flush();
		}
	}
}
